package com.zhongkai.service.impl;

import com.mysql.jdbc.StringUtils;
import com.zhongkai.Bean.PageBean;
import com.zhongkai.app.service.IBaseDao;
import com.zhongkai.app.service.PageQuerDao;
import com.zhongkai.app.service.VersionsService;
import com.zhongkai.jedis.JedisClient;
import com.zhongkai.model.utils.ZhongkaiResult;
import com.zhongkai.model3.SystemVersions;
import org.codehaus.jackson.map.ObjectMapper;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.regex.Pattern;

/**
 * 版本控制
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class VersionsServiceImpl implements VersionsService {


    @Autowired
    private IBaseDao iBaseDao;

    @Autowired
    private PageQuerDao pageQuerDao;


    @Autowired
    private JedisClient jedisClient; //redis

    /**
     * 上传系统
     *
     * @param versions 版本号 1.0.0
     * @param url      路径
     * @param url2     http路径
     */
    @Override
    public ZhongkaiResult uploadSystem(String versions, String url, String url2, String name, String uuid) {
        if (StringUtils.isNullOrEmpty(versions) || StringUtils.isNullOrEmpty(url) || StringUtils.isNullOrEmpty(url2)) {
            return ZhongkaiResult.build(500, "上传失败");
        }

/*        SystemVersions versions1 = (SystemVersions) iBaseDao.get("from SystemVersions sp where sp.versions='" + versions + "'");


        if (versions1 != null) {

            return ZhongkaiResult.build(500, "该版本已存在");
        }*/


        SystemVersions versions1;

        String prc = "^\\d+\\.\\d+\\.\\d+$";

        if (!Pattern.matches(prc, versions)) {

            return ZhongkaiResult.build(500, "版本号格式不合法");
        }

        versions1 = new SystemVersions();

        long millis = new DateTime().getMillis(); //获取当前系统时间戳

        versions1.setFileUrl(url);

        versions1.setFileUrl2(url2);

        versions1.setVersions(versions);

        versions1.setTime(millis);

        versions1.setIs_default(2);  //1为默认 2为非默认

        versions1.setName(name);

        versions1.setUuid(uuid);

        iBaseDao.save(versions1);


        return ZhongkaiResult.ok();

       // versions1 = (SystemVersions) iBaseDao.findOne("from SystemVersions order by id desc");

/*        if (versions1 == null) { //无法查出数据 设当前为默认
            String prc = "^\\d+\\.\\d+\\.\\d+$";

            if (!Pattern.matches(prc, versions)) {

                return ZhongkaiResult.build(500, "版本号格式不合法");
            }

            versions1 = new SystemVersions();


            long millis = new DateTime().getMillis(); //获取当前系统时间戳

            versions1.setFileUrl(url); //设置网络地址

            versions1.setFileUrl2(url2);  //设置文件本地地址

            versions1.setVersions(versions);

            versions1.setTime(millis);

            versions1.setIs_default(1);  //1为默认 2为非默认

            versions1.setName(name);

            versions1.setUuid(uuid);

            iBaseDao.save(versions1);


            ObjectMapper mapper = new ObjectMapper();

            try {

                jedisClient.set("versions", mapper.writeValueAsString(versions1)); //加入缓存

            } catch (IOException e) {
                e.printStackTrace();
                return ZhongkaiResult.build(500, "解析错误");
            }

            return ZhongkaiResult.ok();
        } else {

        }*/


    }

    @Override
    public ZhongkaiResult upload(String versions) {
        SystemVersions versions1 = (SystemVersions) iBaseDao.get("from SystemVersions sp where sp.versions='" + versions + "'");


        if (versions1 != null) {

            return ZhongkaiResult.build(500, "该版本已存在");
        }else {
            return ZhongkaiResult.ok();
        }
    }


    /**
     * 上传历史记录  //Is_default 1为默认 2为非默认
     *
     * @param page 页数
     * @param rows 每页数据数量
     * @param is_default 1默认 2非默认
     */

    @Override
    public ZhongkaiResult uploadSystemList(Integer page, Integer rows,Integer is_default) {
        if (page == 0 || rows == 0 || is_default == 0) {
            return ZhongkaiResult.build(400, "数据不完整");
        }

        try {
            PageBean pageBean = new PageBean();
            pageBean.setCurrentPage(page);
            pageBean.setPageSize(rows);
            DetachedCriteria detachedCriteria = DetachedCriteria.forClass(SystemVersions.class);
            detachedCriteria.add(Restrictions.eq("is_default", is_default)); //已审批列表
            detachedCriteria.addOrder(Order.desc("time")); //根据传入的字段进行降序排序
            pageBean.setDetachedCriteria(detachedCriteria);
            pageQuerDao.pageQuery(pageBean);
            return ZhongkaiResult.ok(pageBean);
        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(405, "查询失败");
        }
    }


    /**
     * 设为默认
     * @param id      系统id
     */
    @Override
    public ZhongkaiResult setDefault(Long id) {
        if (id == 0) {
            return ZhongkaiResult.build(400, "数据不完整");
        }

        SystemVersions systemVersions = (SystemVersions) iBaseDao.get("from SystemVersions sp where sp.id=" + id); // 根据id取出数据

        if (systemVersions == null){
            return ZhongkaiResult.build(400, "此id不存在");
        }

        SystemVersions versions = (SystemVersions) iBaseDao.get("from SystemVersions sp where sp.is_default=1"); // 取出数据库中默认的系统

        if (versions != null){
            versions.setIs_default(2); // 把之前默认修改为非默认
            iBaseDao.update(versions);

        }

        systemVersions.setIs_default(1); //把当前设为默认
        iBaseDao.update(systemVersions);

        ObjectMapper mapper = new ObjectMapper();

        try {

            jedisClient.set("versions", mapper.writeValueAsString(systemVersions)); //加入缓存

        } catch (IOException e) {
            e.printStackTrace();
            return ZhongkaiResult.build(500, "解析错误");
        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(500, "redis连接获取失败");
        }

        return ZhongkaiResult.ok();
    }



    /**
     * 删除
     * @param id      系统id
     */

    @Override
    public ZhongkaiResult removeVer(Long id) {

        if (id == 0) {
            return ZhongkaiResult.build(400, "数据不完整");
        }

        SystemVersions systemVersions = (SystemVersions) iBaseDao.get("from SystemVersions sp where sp.id=" + id); // 根据id取出数据
        if (systemVersions == null){
            return ZhongkaiResult.build(400, "此id不存在");
        }


        if (1 ==  systemVersions.getIs_default()) {
            return ZhongkaiResult.build(400, "默认版本不可删除");
        }

        iBaseDao.delete(systemVersions);
        return ZhongkaiResult.ok();
    }


    /**
     * 取消默认
     * @param id      系统id
     */
    @Override
    public ZhongkaiResult cancelDefault(Long id) {
        if (id == 0) {
            return ZhongkaiResult.build(400, "数据不完整");
        }

        SystemVersions systemVersions = (SystemVersions) iBaseDao.get("from SystemVersions sp where sp.id=" + id); // 根据id取出数据
        if (systemVersions == null){
            return ZhongkaiResult.build(400, "此id不存在");
        }else if (2 ==  systemVersions.getIs_default()){
            return ZhongkaiResult.build(400, "此版本不是默认");
        }



        systemVersions.setIs_default(2); // 把之前默认修改为非默认
        iBaseDao.update(systemVersions);

    //    jedisClient.delete("versions"); //清空缓存

        try {
            jedisClient.expire("versions", 0);//过期时间为0
        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(500, "redis连接获取失败");
        }

        return ZhongkaiResult.ok();
    }
}
